package org.springblade.modules.alimqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.mqtt.server.ServerConsumer;
import com.alibaba.mqtt.server.model.MessageProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.modules.alimqtt.message.MsgPayload;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@ConditionalOnProperty(name = "aliyun.mqtt.enable", havingValue = "true", matchIfMissing = false)
public class AliyunMqttHandler implements CommandLineRunner {
    String first_topic = "door";
    @Resource
    private ServerConsumer serverConsumer;
    @Resource
    private AliyunMsgDispatcher aliyunMsgDispatcher;

    @Override
    public void run(String... args) throws Exception {
        new Thread(() -> {
            try {
                serverConsumer.subscribeTopic(first_topic, (msgId, messageProperties, payload) -> {

                    log.info("Receive:" + msgId + "," + JSONObject.toJSONString(messageProperties) + "," + new String(payload));
                    MsgPayload msgPayload = parseDevice(messageProperties, new String(payload));
                    String receiveTopic = messageProperties.getFirstTopic() + messageProperties.getSecondTopic();
                    log.info("aliyun-mqtt===>Receive:{}===>{}",receiveTopic,new String(payload));
                    log.info("解析后消息{}",JSON.toJSONString(msgPayload));
                    if (null != msgPayload) {
                        aliyunMsgDispatcher.dispatch(receiveTopic, msgPayload);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }


    public MsgPayload parseDevice(MessageProperties messageProperties, String message) {
        String clientId = messageProperties.getClientId();
        Long bornTime = messageProperties.getBornTime();
        String secondTopic = messageProperties.getSecondTopic();
        log.info("aliyun-matt-secondTopic{}",secondTopic);

        List<String> split = Arrays.stream(secondTopic.split("/")).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        if (split.size() < 3) {
            return null;
        }
        MsgPayload msgPayload = new MsgPayload();
        msgPayload.setDeviceNo(split.get(1));
        msgPayload.setMessage(message);
        msgPayload.setClientId(clientId);
        msgPayload.setBornTime(bornTime);
		log.info("aliyun-matt-message{}", JSON.toJSONString(msgPayload));
        return msgPayload;
    }
}
